package com.dankegongyu.demo.http.http.interceptor;

import androidx.annotation.NonNull;

import com.dankegongyu.demo.http.MyApplication;
import com.dankegongyu.demo.http.util.NetworkUtil;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import okhttp3.CacheControl;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;

/**
 * 缓存拦截器
 *
 * @author wupuquan
 * @version 1.0
 * @since 2018/7/6 20:12
 */
public class CacheInterceptor implements Interceptor {

    /**
     * 有网缓存10s，即有网时同一接口请求一次，10s内再次请求取到的数据是OkHttp的本地缓存
     */
    private static final int MAX_AGE = 10;
    /**
     * 离线缓存1周，即断网时请求取到的数据是OkHttp的本地缓存，如果缓存时长超过1周提示请求失败
     */
    private static final int MAX_STALE = 60 * 60 * 24 * 7;

    @Override
    public Response intercept(@NonNull Chain chain) throws IOException {
        Request request = chain.request();
        if (NetworkUtil.isConnected(MyApplication.getInstance())) {
            // 网络缓存
            Response response = chain.proceed(request);
            return response.newBuilder()
                    // Pragma头用来包含实现特定的指令，最常用的是Pragma:no-cache，
                    // 在HTTP/1.1协议中，它的含义和 Cache-Control:no-cache 相同
                    .removeHeader("Pragma")
                    .header("Cache-Control", "public, max-age=" + MAX_AGE)
                    .build();
        } else {
            // 离线缓存
            request = request.newBuilder()
                    .cacheControl(OFFLINE_CACHE)
                    .build();
            return chain.proceed(request);
        }
    }

    private final CacheControl OFFLINE_CACHE = new CacheControl.Builder()
            .onlyIfCached()
            .maxStale(MAX_STALE, TimeUnit.SECONDS)
            .build();
}
